//
//  TJHomeTableViewController.swift
//  WeiBo
//
//  Created by TanJian on 15/12/5.
//  Copyright © 2015年 Joshpell. All rights reserved.
//

import UIKit
import SVProgressHUD

let TJTableViewCellID = "cell"

class TJHomeTableViewController: TJVisitorTableViewController {

    //首页的视图模型
    var userDataListViewModel:TJUserDataListViewModel = TJUserDataListViewModel()
    //刷新控件
    private var ttrefreshControl: TJRefreshControl = TJRefreshControl()
    
    //上拉控件
    private lazy var pullUPView:UIActivityIndicatorView = {
       
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
        
        view.color = UIColor.orangeColor()
        view.sizeToFit()
        
        return view
    }()
    
    //下拉lable
    private lazy var pullDownLable:UILabel = {
        let lable = UILabel()
        
        lable.backgroundColor = UIColor.orangeColor()
        lable.textColor = UIColor.whiteColor()
        lable.font = UIFont.systemFontOfSize(12)
        
        lable.textAlignment = .Center
        lable.hidden = true
        
        var frame = lable.frame
        frame.size = CGSize(width: TJScreen.width, height: 35)
        frame.origin.y = 64 - 35
        lable.frame = frame
        
        return lable
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !userLogon{
            
            visitorVC?.setupVisitor(nil, text: nil)
            return
        }
        
        setupUI()

        loadData()
    }
    
    
    private func setupUI(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: "navigationbar_friendsearch", target: self, action: "goToNextVC")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imgName: "navigationbar_pop", target: self, action: "goToNextVC")
        
        setupTableView()
    }
    
    private func setupTableView(){
        
        tableView.registerClass(TJStatusCell.self, forCellReuseIdentifier: TJTableViewCellID)
        
        //设置cell的高度可变，自动计算
        tableView.rowHeight = UITableViewAutomaticDimension
        //预估cell的高度，越接近越好
        tableView.estimatedRowHeight = 200
        //隐藏分割线
        tableView.separatorStyle = .None
        
        //设置上拉加载的控件
        tableView.tableFooterView = pullUPView
        
        ttrefreshControl.addTarget(self, action: "loadData", forControlEvents: .ValueChanged)
        tableView.addSubview(ttrefreshControl)
    }

    @objc private func goToNextVC() {
        
        let VC = TJTempViewController()
        navigationController?.pushViewController(VC, animated: true)
        
    }
}




//tableview数据源
extension TJHomeTableViewController{

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return userDataListViewModel.userInfoList?.count ?? 0
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(TJTableViewCellID, forIndexPath: indexPath) as! TJStatusCell
        cell.userDataViewModel = userDataListViewModel.userInfoList![indexPath.row]

        return cell
    }
    
    //将要显示某一个cell时调用此方法
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        if !pullUPView.isAnimating() && indexPath.row == userDataListViewModel.userInfoList!.count-1{
            
            pullUPView.startAnimating()
            loadData()
        }
        
    }

}

//下载数据
extension TJHomeTableViewController{
    
    @objc private func loadData(){
    
        userDataListViewModel.loadData(pullUPView.isAnimating()) { (isSuccess,count) -> () in
            if isSuccess{
                self.tableView.reloadData()
                
                //判断是上啦加载就不显示下拉加载信息数的提示
                if !self.pullUPView.isAnimating(){
                    //显示下拉时新加载信息的提示
                    self.showPullDownLable(count)
                }
            }else{
                SVProgressHUD.showErrorWithStatus("请求失败")
            }
            //停止加载
            
            self.endLoad()
        }
    }
    
    
    private func endLoad(){
        pullUPView.stopAnimating()
        ttrefreshControl.endRefresh()
    }
    private func showPullDownLable(count:Int){
        
        //若当前控件正在执行动画，返回
        if self.pullUPView.hidden == false{
            return
        }
        //判断控件是否被添加到指定位置
        if self.pullDownLable.superview == nil {
            if let navController = self.navigationController {
                navController.view.insertSubview(self.pullDownLable, belowSubview: navController.navigationBar)
            }
        }
        
        if count == 0{
            pullDownLable.text = "已经是最新的微博数据了"
        }else{
            pullDownLable.text = "加载了\(count)条微博"
        }
        pullDownLable.hidden = false
        
        //提示框下移显示在顶部
        UIView.animateWithDuration(1) { () -> Void in
            self.pullDownLable.transform = CGAffineTransformMakeTranslation(0, self.pullDownLable.frame.height)
        }
        UIView.animateKeyframesWithDuration(1, delay: 1, options: [], animations: { () -> Void in
            self.pullDownLable.transform = CGAffineTransformIdentity
            }) { (_) -> Void in
            self.pullDownLable.hidden = true
        }
        
    }
    
}

